/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

import FileStructure.ClientRequest;
import FileStructure.FileHandler;
import FileStructure.Response;
import Peer.pTCP;
import Peer.peerRequest.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author user
 */
public class PeerEntity {
    final int MAX_PORT = 15;
    //public int peer_id;
    public String IP;
    public int port;                                                        //port HTTP
    public ArrayList<pTCP> portTCP = new ArrayList<pTCP>();   //PORT TCP
    public ClientRequest request; //dapet dari file torrent
    public Response resp = new Response();

    public boolean downloadComplete = false;
    public boolean isSeeder = false;
    public boolean isDownloading = false;
    public boolean isActive = false;
    final int SPEED = 10000; //10 kbps



    //untuk protokol peer
    public handShakeType        handshake;
    public blockRequest         blockrequest;
    public bitField             bitfield;
    public cancel               cancel;
    public have                 have;
    public keepAliveType        keepalive;
    public piece                piece;

    //piece nomor mana aja yg dimiliki peer
    public byte[] byteField;
    public ArrayList<Integer> havePiece = new ArrayList<Integer>();
    public int currPieceIdx=0;
    //untuk koneksi
    public URL url;
    public URLConnection connection;
    public Socket peerSocket;
    public ServerSocket peerListener;
    public String message;

    //array of byte
    public ArrayList<Byte> byteLoad;
    public byte[] pieceBlock;
    public boolean isHandshake = false;
    public String dir="test/";
    public File f = new File(dir+"downloaded.mp3");

    public PeerEntity(String IP, int port, boolean completed) {
        //super(System.out, 15);
        //this.peer_id = id;
        this.IP = IP;
        this.port = port;
        this.isSeeder = completed;
        this.request = new ClientRequest("");

//        try {
//            System.out.println("Listening on port "+ port);
//            this.peerListener = new ServerSocket(port);
//            this.peerSocket = this.peerListener.accept();
//        } catch (UnknownHostException ex) {
//            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }

    public void createListener(){
        try {
            System.out.println("Listening on port "+ port);
            this.peerListener = new ServerSocket(port);
            this.peerSocket = this.peerListener.accept();
        } catch (UnknownHostException ex) {
            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void createSenderSocket(String IP, int port){
        try {
            this.peerSocket = new Socket(IP, port);
        } catch (UnknownHostException ex) {
            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void openConnection(){
        try {

            url = new URL("http://localhost:8080/TrackerWeb/ReverseServlet");
            connection = url.openConnection();
            connection.setDoOutput(true);
        } catch (IOException ex) {
            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addPortTCP(int p, String service) {
        pTCP pr = new pTCP(p,service);
        this.portTCP.add(pr);
       // System.out.println(pr.port);
    }

    public void removePortTCP(int p) {
        this.portTCP.remove(p);
    }

    public boolean isSeeder(String filename) {
        if (filename.equalsIgnoreCase(this.request.file_name)) {
            if (this.request.left == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public void readFileTorrent(String dir, String torrentName){
        try {
            //set filename, announce, file length, hash pieces
            FileHandler fh = new FileHandler();
            fh.readTorrent(dir, torrentName);
            this.request.announceURL = fh.announce;
            this.request.file_name = fh.fileName;
            this.request.file_length = fh.fileLength;
            this.request.setPieceHashVal(fh.piecesHashVal);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PeerEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //create split buffer jika punya filenya
    public byte[][] createSplitBuffer(String dir, String namafile) throws IOException {
        FileHandler fh = new FileHandler();
        File file = new File(dir + namafile);
        int size = (int)fh.getFileSize(dir + namafile);
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos;
        byte buffer[][] = new byte[size][fh.pieceLength];
        int count = 0;
        while (true) {
            int i = fis.read(buffer[count], 0, fh.pieceLength);
            if (i == -1) {
                break;
            }
            count++;
        }
        fis.close();
        return buffer;
    }
}
